<template>
  <div class="app-container  bg-gray">
    <transition name="fade-transform" mode="out-in">
      <router-view />
    </transition>
    <el-row v-if="isShow" class="box-1">
      <el-col :span="24">
        <el-card>
          <div class="header">
            <div>
              <el-button v-if="queryMatch(46)" type="success" class="bg-green" icon="el-icon-circle-plus" @click="toCreateNews">发布新闻</el-button>
              <el-button v-if="queryMatch(161)" type="warning" icon="el-icon-circle-plus" @click="toAdd">新增分类</el-button>
            </div>
          </div>
          <el-table
            v-loading="tableLoading"
            :data="tableData"
            :max-height="tableMaxHeight"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            row-key="id"
            border
            default-expand-all
            highlight-current-row
            @sort-change="handleSortChange">
            <el-table-column prop="name" label="类型标题" min-width="260">
              <template slot-scope="scope">
                <router-link :to="`/information/newsType/list?id=${scope.row['id']}`">
                  <el-tag :effect="!scope['row'].cid?'dark':'plain'" type="primary">
                    {{ scope.row.name }}{{ scope['row']['type']===2?'【专题】' : '' }}
                  </el-tag>
                </router-link>
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序权重" width="120" header-align="center" align="center" sortable />
            <el-table-column v-if="queryMatch(162)" label="状态" min-width="80" header-align="center" align="center">
              <template slot-scope="scope">
                <div @click="queryMatch(162)?setState(scope['row']):''">
                  <el-tag :type="scope['row'].status===0?'danger':'success'">{{ scope.row.status===0?'已隐藏':'已显示' }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" header-align="center" align="center">
              <template slot-scope="scope">
                <el-tooltip content="新闻列表" placement="top">
                  <el-button size="small" type="primary" icon="el-icon-more" circle style="margin-left: 10px;" @click="toNewsList(scope['row'])"/>
                </el-tooltip>
                <el-button v-if="queryMatch(162)" type="success" class="bg-green" size="small" icon="el-icon-edit" circle style="margin-left: 10px;" @click="toEdit(scope['row'])"/>
                <el-button v-if="queryMatch(163)" type="danger" size="small" icon="el-icon-delete" circle @click="toDelete(scope['row'])" />
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page.sync="currentPage"
            :page-size="pageSize"
            :page-sizes="pageSizes"
            :total="total"
            class="pagination"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"/>
        </el-card>
      </el-col>
    </el-row>

    <!--分类弹窗-->
    <el-dialog :visible.sync="dialogVisible" :modal="false" :title="form.title" width="500px" class="dialog" center @close="resetDialog('form')">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="名称" prop="name" style="width: 80%;">
          <el-input v-model="form.name"/>
        </el-form-item>
        <el-form-item label="上级分类：">
          <el-cascader
            v-model="form.cid"
            :options="typeList"
            :props="{
              expandTrigger: 'hover',
              checkStrictly: true
            }"
            clearable/>
        </el-form-item>
        <el-form-item label="图标">
          <ws-upload-single-img v-model="form['icon']" :path="form['icon']"/>
        </el-form-item>
        <el-form-item v-if="form.title!=='添加专题'" label="权重" prop="sort">
          <el-input-number v-model="form.sort"/>
          <div class="remark">*注：权重越大排序越前</div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form['status']">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否设为专题" prop="type">
          <el-radio-group v-model="form['type']">
            <el-radio :label="2">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDialog('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { handleSortChange, handleSizeChange, handleCurrentChange } from '../../../utils/table';
  import { validatNonSpecialCharacters } from '@/utils/validate';
  export default {
    data() {
      return {
        isShow: false,
        searchTerms: {
          searchValue: ''
        },

        // 类型列表
        typeList: [],

        // 弹出框相关数据
        dialogVisible: false,
        form: {
          title: '添加分类',
          id: '',
          name: '',
          status: 1,
          type: 1,
          sort: '',
          cid: ''
        },
        rules: {
          name: [{ required: true, message: '请输入标题', trigger: 'change' }],
          sort: [{ required: true, message: '请输入权重', trigger: 'change' }],
          status: [{ required: true, message: '请选择状态', trigger: 'change' }]
        },

        // 表格相关数据
        tableMaxHeight: document.documentElement.clientHeight - 280,

        // 表格相关参数
        tableLoading: false,
        currentPage: 1,
        pageSize: this.$store.getters.userInfo.pageSize,
        pageSizes: [10, 20, 50, 100, 1000],
        total: 0,
        tableData: []
      }
    },
    watch: {
      $route(to) {
        if (to.name === '新闻类型') {
          this.getData({ sortName: 'sort', sortOrder: 'desc' });
          setTimeout(() => {
            this.isShow = true
          }, 500)
        } else {
          this.isShow = false
        }
      }
    },
    created() {
      if (this.$route.name === '新闻类型') {
        this.isShow = true;
        this.getData({ sortName: 'sort', sortOrder: 'desc' });
        if (this.queryMatch(161)) {
          this.loadTypeList()
        }
      }
    },

    methods: {
      handleCurrentChange, handleSizeChange, handleSortChange,
      getData(order) {
        this.tableLoading = true
        order || (order = {})
        const url = 'lookarticles/typeList'
        const data = {
          page_no: this.currentPage,
          page_size: this.pageSize,
          search: this.searchTerms.searchValue,
          type: 1
        }
        order.sortName && (data.sortName = order.sortName);
        order.sortOrder && (data.sortOrder = order.sortOrder);
        this.$store.dispatch('GetConnect', { url, data }).then(res => {
          this.tableData = res.data.rows;
          this.total = res.data.total;
          this.tableLoading = false;
        }).catch(e => {
          this.tableLoading = false;
          this.$message.error(e.msg + ',请刷新或联系管理员');
        })
      },

      loadTypeList() {
        const url = 'lookarticles/allTypeList'
        this.$store.dispatch('GetConnect', { url }).then(res => {
          this.typeList = res.data;
        }).catch(e => {
          this.$message.error(e.msg + ',请刷新或联系管理员')
        })
      },

      toNewsList(row) {
        this.isShow = false
        this.$router.push({
          path: '/information/newsType/list',
          query: { id: row.id }
        })
      },

      toCreateNews() {
        this.isShow = false
        const query = { title: '发布新闻' }
        this.$router.push({
          path: '/information/newsType/modify',
          query: query
        })
      },

      /**
       * 设置当前新闻的状态
       * row: 当前点击的行的数据
       */
      setState(row) {
        row.status = row.status === 0 ? 1 : 0
        const url = 'lookarticles/updateStatus'
        const data = { id: row.id, status: row.status }
        this.$store.dispatch('GetConnect', { url, data }).then(res => {
          this.$message.success('修改新闻类型状态成功，状态：' + (row.status === 1 ? '已显示' : '已隐藏'));
          this.getData({ sortName: 'sort', sortOrder: 'desc' });
        }).catch(() => {
          row.status = row.status === 0 ? 1 : 0
          this.$message.error('修改新闻类型状态失败，请刷新或联系管理员')
        })
      },

      /**
       * 删除新闻类型
       * row: 当前点击的行的数据
       */
      toDelete(row) {
        this.$confirm('此操作将把该新闻类型删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const url = 'lookarticles/delType/' + row.id
          this.$store.dispatch('GetConnect', { url }).then(res => {
            this.$message.success(res.msg)
            this.getData({ sortName: 'sort', sortOrder: 'desc' });
          }).catch(e => {
            this.$message.error(e.msg + ',请刷新或联系管理员!')
          })
        })
      },

      // 添加分类
      toAdd() {
        this.form = {
          title: '添加分类',
          name: '',
          cid: '',
          type: 1,
          status: 1,
          sort: 0,
          icon: null
        };
        this.dialogVisible = true;
      },
      // 编辑分类
      toEdit(row) {
        this.dialogVisible = true;
        row.title = '编辑分类';
        this.form = Object.assign({}, row);
        this.form.cid = [row.cid];
        console.log(this.form)
      },

      /**
       * 弹窗表单提交方法,通过判断有没有form_id执行添加或编辑操作
       * formName: form表单中ref的值,即表单名
       */
      submitDialog(formName) {
        this.$refs[formName].validate((valid) => { // 表单验证
          if (valid) {
            const url = this.form.id ? '/lookarticles/updateType' : '/lookarticles/addType';
            const data = this.form;
            data.cid = data.cid[this.form.cid.length - 1];
            if (!validatNonSpecialCharacters(this.form['name'])) {
              this.$message.error('新闻类型不能包含特殊字符');
              return;
            }
            this.$store.dispatch('GetConnect', { url, data }).then(res => {
              this.dialogVisible = false
              this.$message.success(res.msg)
              this.getData({ sortName: 'sort', sortOrder: 'desc' });
              this.loadTypeList();
            }).catch(e => {
              this.$message.error(e.msg + ',请刷新或联系管理员!')
            })
          } else {
            this.$message.error('提交失败,请检查必填项')
          }
        })
      },
      resetDialog(formName) {
        this.$refs[formName].resetFields()
      }
    }
  }
</script>

<style lang="scss" type="text/scss" scoped>
  @import '../../../styles/index.scss';
  .box-1 {
    max-width: 1200px;
    .header {
      @include flex-row(center, space-between);
      padding-bottom: 15px;
      flex-wrap: wrap;
      > div {
        @include flex-row(center, flex-start);
        flex-wrap: wrap;
        width: 100%;
      }
      .search-input {
        width: 240px;
      }
      .do-btn {
        @extend .bg-green;
        margin-left: 6px;
      }
    }
  }
  .el-tag {
    cursor: pointer;
  }
</style>
